import tkinter as tk
import tkinter.messagebox 
import random

# 游戏窗口大小（方格数量）
ROWS = 10
COLS = 10
# 地雷数量
MINES = 10
# 方格大小（像素）
CELL_SIZE = 30

# 初始化游戏窗口
root = tk.Tk()
root.title("扫雷游戏")

# 创建用于存储方格按钮的二维列表
buttons = [[None for _ in range(COLS)] for _ in range(ROWS)]
# 用于存储每个方格是否是地雷的二维列表，True表示是地雷，False表示不是
mines = [[False for _ in range(COLS)] for _ in range(ROWS)]
# 用于存储每个方格周围地雷数量的二维列表
nearby_mines_count = [[0 for _ in range(COLS)] for _ in range(ROWS)]

# 随机放置地雷
def place_mines():
    count = 0
    while count < MINES:
        row = random.randint(0, ROWS - 1)
        col = random.randint(0, COLS - 1)
        if not mines[row][col]:
            mines[row][col] = True
            count += 1

# 计算每个非地雷方格周围的地雷数量
def calculate_nearby_mines():
    for row in range(ROWS):
        for col in range(COLS):
            if not mines[row][col]:
                count = 0
                for r in range(max(0, row - 1), min(ROWS-1, row + 1) + 1):
                    for c in range(max(0, col - 1), min(COLS-1, col + 1) + 1):
                        if mines[r][c]:
                            count += 1
                nearby_mines_count[row][col] = count

# 创建方格按钮并绑定点击事件
def create_buttons():
    

    # 创建按钮，指定使用上面定义的样式

    for row in range(ROWS):
        for col in range(COLS):
            button = tk.Button(root, text="", width=2, height=1,bg="blue",
                               command=lambda r=row, c=col: click_cell(r, c))
            button.grid(row=row, column=col)
            buttons[row][col] = button

# 点击方格的处理函数
def click_cell(row, col):
    if mines[row][col]:
        game_over()
    else:
        reveal_cell(row, col)

# 显示方格及其周围非地雷方格（若周围方格的周围地雷数为0，则递归显示其周围方格）
def reveal_cell(row, col):
    msg = nearby_mines_count[row][col]
    buttons[row][col].config(text= str(msg) if msg >0 else "" , bg="white",fg='black',state=tk.DISABLED)
    if nearby_mines_count[row][col] == 0:
        for r in range(max(0, row - 1), min(ROWS-1, row + 1) + 1):
            for c in range(max(0, col - 1), min(COLS-1, col + 1) + 1):
                if buttons[r][c]['state'] == tk.NORMAL and not mines[r][c]:
                    reveal_cell(r, c)

# 游戏结束函数，显示所有地雷位置等信息
def game_over():
    
    for row in range(ROWS):
        for col in range(COLS):
            if mines[row][col]:
                buttons[row][col].config(text="@",bg="red",fg='black',state=tk.DISABLED)
    tk.messagebox.showinfo("游戏结束", "你踩到地雷了，游戏结束！")

# 主函数，启动游戏流程
def main():
    place_mines()
    calculate_nearby_mines()
    create_buttons()
    root.mainloop()

if __name__ == "__main__":
    main()